package com.example.apps

import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.apps.databinding.ActivityNetAppBinding
import com.example.lib_adapter.BaseQuickMultipleAdapter
import com.example.lib_base.BaseActivity
import io.virtualapp.hook_sdk.app.InstallAppUtils
import io.virtualapp.hook_sdk.dao.RiNotesService
import io.virtualapp.hook_sdk.models.InstallAppBean
import kotlinx.coroutines.launch
import java.io.File

//path一定至少是两级目录，而且每个模块的第一级（apps）都不能一样
@Route(path="/apps/NetAppActivity")
class NetAppActivity : BaseActivity<ActivityNetAppBinding,NetViewModel>() {
    val appUtils by lazy { InstallAppUtils() }
    val netAdapter by lazy { NetAdapter() }
    lateinit var path:String
    lateinit var alertDialog:AlertDialog

    val apkPath by lazy {
        getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!.absolutePath
    }
    override fun createVM(): NetViewModel {
        return NetViewModel()
    }

    override fun createV(): ActivityNetAppBinding {
        return ActivityNetAppBinding.inflate(layoutInflater)
    }

    override fun bindState() {

        lifecycleScope.launch {
            vm.mutableContainer.uiFlow.collect{
                val state = it as NetAppState
                if(state.appState){
                    Log.i("===数据",state.apps.toString())
                    netAdapter.addAll(state.apps)
                }else if(state.startState){
                    alertDialog = AlertDialog.Builder(this@NetAppActivity).setTitle("下载")
                        .setMessage("下载中，请稍后").create()
                    alertDialog.show()
                }else if(state.doneState){
                    alertDialog.dismiss()
                    if (!File(apkPath).exists()){
                        Log.i("===","下载失败")
                        return@collect
                    }
                    Toast.makeText(this@NetAppActivity, "下载完成", Toast.LENGTH_SHORT).show()
                    var dialog = AlertDialog.Builder(this@NetAppActivity).setTitle("安装提醒")
                        .setMessage("下载完成，是否安装?")
                        .setPositiveButton("安装",object :OnClickListener{
                            override fun onClick(dialog: DialogInterface?, which: Int) {
                                val bean = InstallAppBean()
                                bean.app_time = System.currentTimeMillis()
                                bean.apk_path = path
                                bean.app_name = state.apps[0].app_package
                                val installApp = RiNotesService.getInstance().insertApp(bean)
//                                val installApp = appUtils.installApp()
                                Toast.makeText(this@NetAppActivity, "安装"+installApp, Toast.LENGTH_SHORT).show()
                                dialog?.dismiss()
                            }
                        }).setNegativeButton("取消",object :OnClickListener{
                            override fun onClick(dialog: DialogInterface?, which: Int) {
                                dialog?.dismiss()
                            }
                        })
                        .create()
                    dialog.show()
                }

            }
        }
    }

    override fun initData() {
        vm.selClientApp()
    }

    override fun initView() {

        vb.ivBack.setOnClickListener {
            finish()
        }

        vb.appsRv.apply {
            layoutManager=GridLayoutManager(this@NetAppActivity,3)
            adapter=netAdapter
        }
        netAdapter.setOnItemClickListener(object :BaseQuickMultipleAdapter.OnItemClickListener{
            override fun onItemClick(position: Int) {
                val entity = netAdapter.getData().get(position)
                path=apkPath+"/"+entity.appName+".apk"

                AlertDialog.Builder(this@NetAppActivity).setTitle("下载")
                    .setMessage("请确认是否下载").setPositiveButton("确认",object :OnClickListener{
                        override fun onClick(dialog: DialogInterface?, which: Int) {
                            //下载
                            vm.download(entity.apkUrl,path)
                        }

                    }).setNegativeButton("取消",object :OnClickListener{
                        override fun onClick(dialog: DialogInterface?, which: Int) {
                            dialog?.dismiss()
                        }

                    }).create().show()

            }
        })
    }
}